package com.objetdirect.gwt.umldrawer.server.services;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.objetdirect.gwt.umldrawer.server.dao.ProjectDAO;
import com.objetdirect.gwt.umldrawer.shared.dto.ProjectDto;
import com.objetdirect.gwt.umldrawer.shared.services.ProjectService;

@Service("projectService")
public class ProjectServiceImpl implements ProjectService {

	@Autowired
	private ProjectDAO projectDao;

	@PostConstruct
	public void init() throws Exception {
	}

	@PreDestroy
	public void destroy() {
	}

	public ProjectDto findProject(int projectId) {

		return projectDao.findById(projectId);

	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void saveProject(int projectId, String name, String type,
			String adminEmail) throws Exception {

		ProjectDto projectDTO = projectDao.findById(projectId);

		if (projectDTO == null) {
			projectDTO = new ProjectDto(projectId, name, type, adminEmail);
			projectDao.persist(projectDTO);
		}

	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void updateProject(int projectId, String name, String type,
			String adminEmail) throws Exception {

		ProjectDto projectDTO = projectDao.findById(projectId);

		if (projectDTO != null) {
			projectDTO.setProjectName(name);
			projectDTO.setProjectType(type);
			projectDTO.setProjectAdminMail(adminEmail);
		}

	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void deleteProject(int projectId) throws Exception {

		ProjectDto projectDTO = projectDao.findById(projectId);

		if (projectDTO != null)
			projectDao.remove(projectDTO);

	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void saveOrUpdateProject(int projectId, String name, String type,
			String adminEmail) throws Exception {

		ProjectDto projectDTO = new ProjectDto(projectId, name, type,
				adminEmail);
		projectDao.merge(projectDTO);
	}

}
